package com.yuge.yugecse.util.generic

import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import androidx.core.content.edit
import java.util.HashSet
import java.lang.Exception

/**
 * Created by Administrator on 2015/3/20.
 * 配置文件辅助类
 */
class ConfigUtil(context: Context, filename: String) {

    private val config: SharedPreferences =
        context.getSharedPreferences(filename, Context.MODE_PRIVATE)

    /**
     * 写入数据
     * @param key
     * @param data
     */
    @Suppress("unchecked_cast")
    fun <T> put(key: String, data: T) = config.edit(true) {
        when (data) {
            is Int -> putInt(key, data)
            is Long -> putLong(key, data)
            is Boolean -> putBoolean(key, data)
            is Float -> putFloat(key, data)
            is Set<*> -> putStringSet(key, data as Set<String>)
            else -> putString(key, data.toString())
        }
    }

    /**
     * 删除key
     * @param key
     */
    fun removeKey(key: String) = config.edit(true) { remove(key) }

    /**
     * 读取数据
     * @param key
     * @param defaultValue
     * @return
     */
    @Suppress("UNCHECKED_CAST")
    operator fun <T : Any> get(key: String, defaultValue: T): T {
        return when (defaultValue) {
            is Int -> config.getInt(key, (defaultValue as Int)) as T
            is Long -> config.getLong(key, (defaultValue as Long)) as T
            is Boolean -> config.getBoolean(key, (defaultValue as Boolean)) as T
            is Float -> config.getFloat(key, (defaultValue as Float)) as T
            is Set<*> -> config.getStringSet(key, defaultValue as Set<String>) as T
            else -> config.getString(key, defaultValue as String) as T
        }
    }

    /**
     * 是否包含某个值
     * @param key
     * @return
     */
    operator fun contains(key: String): Boolean = config.contains(key)

    /**
     * 清空所有数据
     */
    fun clear() = config.edit(true) { clear() }

    /**
     * 获得所有数据
     * @return
     */
    val all: Map<String, *> get() = config.all

}